<template>
  <div class="create">
    <a-form :form="form" @submit="handleSubmit">
      <!--标题-->
      <a-form-item label="标题">
        <a-input
          allowClear
          size="large"
          placeholder="文章标题(1-50)个字符"
          v-decorator="['title', { rules: [{
            min: 5,
            max: 50,
            whitespace: true,
            required: true,
            message: '请输入合格文章标题(5-50)个字符',
          }] }]"
        />
      </a-form-item>
      <!--内容-->
      <a-form-item label="内容" required>
        <client-only>
          <mavon-editor
            v-model="content"
            placeholder="开始创作吧..."
            :shortCut="false"
            codeStyle="atom-one-dark"
            @imgAdd="imageAdd"
            @imgDel="imageRemove"
            ref="mavon"
            style="z-index: 0;min-height: 800px;margin-top: 10px"
          />
        </client-only>
      </a-form-item>

      <!--文章配图-->
      <a-form-item label="文章配图" required>
        <a-upload-dragger
          v-decorator="['imgUrl', {
              initialValue: '',
              rules: [{ required: true, message: '请选择文章配图...' }]
            }]"
          name="article-image"
          :action="uploadUrl"
          :remove="removeImage"
          @change="handleChange"
        >
          <p class="ant-upload-drag-icon">
            <a-icon type="inbox" />
          </p>
          <p class="ant-upload-text">点击或者拖拽图片上传</p>
        </a-upload-dragger>
      </a-form-item>

      <!-- 选择项-->
      <a-row :gutter="20">
        <a-col :xs="24" :sm="8" :xl="8" :xxl="8">
          <a-form-item label="类型" >
            <a-select size="large" placeholder="选择分类..."
              v-decorator="[
                'type',
                { initialValue: 0,
                  rules: [{ required: true, message: '请选择一个类型...' }]
                   },]">
              <a-select-option :value="0">原创</a-select-option>
              <a-select-option :value="1">转载</a-select-option>
            </a-select>
          </a-form-item>

        </a-col>
        <a-col :xs="24" :sm="8" :xl="8" :xxl="8">
          <a-form-item label="分类" >
            <a-select size="large"
                      allowClear
                      placeholder="选择分类..."
                      v-decorator="[
                        'category',
                        { rules: [{ required: true, message: '请选择一个分类...' }] },
                      ]">
              <a-select-option :value="item" v-for="(item, index) in items" :key="index">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>

        </a-col>
        <a-col :xs="24" :sm="8" :xl="8" :xxl="8">
          <a-form-item label="标签" >
            <a-select size="large"
                      allowClear
                      mode="multiple"
                      placeholder="选择标签..."
                      v-decorator="[
                        'tags',
                        { rules: [{ required: true, message: '请至少选择一个标签...' }] },
                      ]">
              <a-select-option :value="item" v-for="(item, index) in items" :key="index">
                {{ item }}
              </a-select-option>
            </a-select>
          </a-form-item>

        </a-col>
      </a-row>

      <!--描述-->
      <a-form-item label="描述">
        <a-textarea
          allowClear
          :rows="4"
          placeholder="文章描述(1-150)个字符"
          v-decorator="['abstract', { rules: [{
            min: 1,
            max: 150,
            whitespace: true,
            required: true,
            message: '请输入合格文章描述(1-150)个字符',
          }] }]"
        />
      </a-form-item>

      <a-form-item style="text-align: center">
        <a-button type="primary" html-type="submit" size="large" ghost shape="round">发布</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
  import app from "../../../../app"
  const uploadUrl = `${app.api}/api/${app.apiVersion}/admin/articleImage/`
  export default {
    name: "create",
    layout: "admin",
    head: ()=>({ title: `发布文章 - ${app.name}` }),
    beforeCreate() {
      this.form = this.$form.createForm(this, { name: 'create' })
    },
    data: ()=>({
      uploadUrl,
      items: [
        "python",
        "css",
        "nuxt",
        "vue",
        "mysql",
        "golang",
        "python3",
        "redis",
        "html",
        "web",
        "life",
        "linux",
        "ubuntu",
        "centos",
        "nodejs",
        "js",
        "typescript",
        "生活",
        "框架",
        "感悟",
        "前端",
        "后端",
        "资讯",
        "开发工具",
        "小技巧",
        "教程",
        "优化",
        "面试",
        "公众号",
        "设计模式",
        "vuetify",
        "echo",
        "小程序",
        "AI",
        "工具",
        "chrome",
        "fireFox",
        "数据库",
        "服务器",
        "UI",
        "正则表达式",
        "gorm",
        "jwt",
        "json",
        "nginx"
      ],
      imgUrl: "",
      content: "",
    }),
    methods: {
      handleSubmit(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err && this.content) {
            values.imgUrl = this.imgUrl
            values.author = this.$store.state.user.username;
            values.content = this.content
            // 提交文章
            this.$axios.$post(`${app.api}/api/${app.apiVersion}/admin/article/`, values)
              .then((resp)=>{
                if (resp.code === 200) {
                  this.$message.success(resp.msg);
                  this.$router.push({ path:"/admin/article/list/" })
                  this.form.resetFields()
                }else {
                  if (resp.data.Number === 1062) {
                    this.$message.warning("文章已存在!")
                  }else {
                    this.form.resetFields()
                    this.$message.warning(resp.msg)
                  }
                }
              }).catch((err)=>{
                // 错误处理
              this.form.resetFields()
            })
          }else {
            this.$message.warning("数据验证错误或者文章内容为空")
          }
        })
      },
      handleChange(info) {
        const status = info.file.status;
        if (status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (status === 'done') {
          this.imgUrl = info.file.response.data;
          this.$message.success(`${info.file.name} 上传成功`);
        } else if (status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`);
        }
      },
      imageAdd(pos, file) {
        let formdata = new FormData();
        formdata.append('article-image', file);
        this.$axios.$post(uploadUrl, formdata)
          .then((res)=>{
            if (res.code === 200 ) {
              this.$refs.mavon.$img2Url(pos, res.data);
              this.$message.success("添加图片成功")
            }else {
              this.$message.error("添加图片失败")
            }
          }).catch((error)=>{
          this.$message.error(error)
        })
      },
      imageRemove (filename) {
        this.$axios.$delete(uploadUrl, { data: { name: filename[0] } })
          .then((res)=>{
            if (res.code === 200) {
              this.$message.success("移除图片成功")
            }else {
              this.$message.warning("移除图片失败")
            }
          }).catch((error)=>{
          this.$Message.error(error)
        })
      },
      // 文章封面
      removeImage (file, fileList) {
        this.$axios.$delete(uploadUrl, { data: { name: this.imgUrl } })
          .then((res)=>{
            if (res.code === 200) {
              this.imgUrl = "";
              this.$message.success("移除图片成功")
            }else {
              this.$message.warning("移除图片失败")
            }
          }).catch((error)=>{
          this.$message.error(error)
        })
      },
    }
  }
</script>

<style scoped>

</style>
